package com.marketingexpert.controller.statemgnt;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.marketingexpert.domain.User;
import com.marketingexpert.domain.VisitRecord;
import com.marketingexpert.exception.MarketingExpertException;
import com.marketingexpert.service.statreport.StatReportService;
import com.marketingexpert.service.statreport.openflashchart.Graph;
import com.marketingexpert.service.usermgnt.UserService;
import com.marketingexpert.util.Resources;

public class OutputDataController implements Controller {

	private static final String VISIT_SOURCE_SINA = "sina";
	private static final String VISIT_SOURCE_TENCENT = "tencent";

	private static Logger logger = Logger.getLogger(OutputDataController.class);

	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	private StatReportService statReportService;

	private UserService userService;

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		String parentUserId = (String) request.getSession().getAttribute("parentUserId");

		User parentUser = getUserService().queryUserByUId(parentUserId);

		Map<String, List<VisitRecord>> visitRecordRecentFif = this.createDataSet(parentUser);
		
		List<String> visitTotal = new ArrayList<String>();
		List<String> visitSina = new ArrayList<String>();
		List<String> visitTencent = new ArrayList<String>();

		List<String> labels = new ArrayList<String>();

		Calendar now = Calendar.getInstance();
		now.add(Calendar.DATE, -30);
		int _visitPeek = 0;
		int _totalTmp = 0;
		
		int _dayOfSina = 0;		
		int _dayOfTencent = 0;
		
		for (int i = 0; i < 30 ; i++) {
			now.add(Calendar.DATE, 1);
			java.util.Date _d = now.getTime();
			String _matchDate = sdf.format(_d);
			String key = _matchDate.substring(_matchDate.indexOf("-") + 1,
					_matchDate.length());
			List<VisitRecord> _visitRecords = visitRecordRecentFif.get(key);
			
			if (_visitRecords == null || _visitRecords.size() <= 0) {
				visitTotal.add("0");
				visitSina.add("0");
				visitTencent.add("0");
				_totalTmp = 0;
			} else if (_visitRecords.size() == 1) {
				if (_visitRecords.get(0).getSource().equals(VISIT_SOURCE_SINA)) {
					visitSina.add(String.valueOf(_visitRecords.get(0)
							.getActivityVc()));
					visitTotal.add(String.valueOf(_visitRecords.get(0)
							.getActivityVc()));
					visitTencent.add("0");
				} else {
					visitTencent.add(String.valueOf(_visitRecords.get(0)
							.getActivityVc()));
					visitTotal.add(String.valueOf(_visitRecords.get(0)
							.getActivityVc()));
					visitSina.add("0");
				}
				_totalTmp = _visitRecords.get(0).getActivityVc();
			} else {
				for (VisitRecord vr : _visitRecords) {
					if (vr.getSource().equals(VISIT_SOURCE_SINA)) {
						_dayOfSina += vr.getActivityVc();
					} else {
						_dayOfTencent += vr.getActivityVc();
					}
					_totalTmp += vr.getActivityVc();
				}
				visitTencent.add(String.valueOf(_dayOfTencent));
				visitSina.add(String.valueOf(_dayOfSina));
				visitTotal.add(String.valueOf(_totalTmp));
			}
			
			if(_totalTmp > _visitPeek) {
				_visitPeek = _totalTmp;
			}
			_totalTmp = 0;
			_dayOfSina = 0; 
			_dayOfTencent = 0; 
			String[] keys = key.split("-");
			labels.add(keys[0] + "." + keys[1]);
		}

		Graph g = new Graph();
		// Spoon sales, March 2007
		g.title(Resources.getString("OutputDataController.statIMGTitle"), "{font-size: 15px;}");
		g.set_data(visitTotal);
		g.set_data(visitSina);
		g.set_data(visitTencent);
		
		g.line(2, "0x9933CC", "", 15, 2);
		g.line_hollow("2", "4", "#FF0000", "", "15");
		g.line_hollow("2", "4", "0x80a033", "", "15");

		g.set_x_labels(labels);
		g.set_x_label_style("8", "#FF0000", 0, 1, "");

		// set the Y max
		
		if(_visitPeek % 5 != 0) {
			for(int i=1; i<11; i++) {
				if((_visitPeek + i) % 5 == 0) {
					_visitPeek += i;
					break;
				}
			}
		}
		
		_visitPeek = _visitPeek < 10?10:_visitPeek;
		
		g.set_y_max(_visitPeek);
		g.set_y_label_style("8", "#FF0000");
		
		g.y_label_steps(5);
		
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(g.render());
		return null;
	}

	public Map<String, List<VisitRecord>> createDataSet(User parentUser) {
		try {
			Map<String, List<VisitRecord>> statResults = new HashMap<String, List<VisitRecord>>();
			Map<String, Object> params = new HashMap<String, Object>();
			Calendar now = Calendar.getInstance();
			now.add(Calendar.DATE, 1);
			for (int i = 0; i < 30; i++) {
				now.add(Calendar.DATE, -1);
				java.util.Date _d = now.getTime();
				String _matchDate = sdf.format(_d);
				params.put("parentUserId", parentUser.getId());
				params.put("visitTime", _matchDate);
				List<VisitRecord> visitRecords = getStatReportService()
						.queryVisitRecord(params);
				if (visitRecords == null || visitRecords.size() <= 0) {
					statResults.put(_matchDate.substring(_matchDate
							.indexOf("-") + 1, _matchDate.length()), null);
					continue;
				}
				statResults.put(_matchDate.substring(
						_matchDate.indexOf("-") + 1, _matchDate.length()),
						visitRecords);
			}

			return statResults;
		} catch (MarketingExpertException e) {
			throw e;
		}

	}

	public StatReportService getStatReportService() {
		return statReportService;
	}

	public void setStatReportService(StatReportService statReportService) {
		this.statReportService = statReportService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
